﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using BesAsm.Emgaats.Core;
using BesAsm.Framework.MsAccessUtilities;
using BesAsm.Framework.Reporting;

namespace BesAsm.Emgaats.ModelBuilder
{
  /// <summary>
  /// Provides methods to write stormwater controls files
  /// </summary>
  public class StormwaterControlsBuilder
  {
    private string _dbPath;
    private Model _model;
    private AccessHelper _accessHelper;

    private const string STORMWATER_CONTROLS_ACCESS_DB = "StormwaterControls_v12.mdb";

    public StormwaterControlsBuilder(Model model)
    {      
      if (model.State < ModelState.Assembled)
        throw new ModelStateException(model.State, ModelState.Assembled, 
          "Unable to create stormwater controls builder: Model not yet built.");

      _model = model;
      _dbPath = Path.Combine(model.GetPathIfSet(ModelPathComponent.RootFolder), 
        STORMWATER_CONTROLS_ACCESS_DB);

      WriteStormwaterControlsDatabase();
    }

    private void WriteStormwaterControlsDatabase()
    {
      Messenger.ReportMessage("Copying StormwaterControls_v12.mdb", ReportableMessageType.Info);
      FileStream outStream = null;
      try
      {
        outStream = new FileStream(_dbPath, FileMode.Create);
        byte[] data = Properties.Resources.StormwaterControls_V12;
        outStream.Write(data, 0, data.Length);
        outStream.Flush();
      }
      finally
      {
        if (outStream != null)
          outStream.Close();
      }
    }


    public void DeployStormwaterControls()
    {
      try
      {
        Messenger.ReportMessage("Deploying stormwater controls", ReportableMessageType.Info);
        _accessHelper = new AccessHelper(_dbPath);
        string databaseNameWithoutExtension = 
          Path.GetFileNameWithoutExtension(_model.GetPathIfSet(ModelPathComponent.Pgdb));
        _accessHelper.UpdateField("_linktablelist", "LinkDatabase", databaseNameWithoutExtension);
        _accessHelper.UpdateField("_linktablelist", "LinkDatabase",
          "[LocalTable] IN ('MODEL_DSCS_CALCULATED','MODEL_SSCS_CALCULATED')", "ModelBuild");
        _accessHelper.ExecuteMacro("_Build_InflowControls_ALL_Silent");
      }
      finally
      {
        if (_accessHelper != null)
          _accessHelper.Dispose();
      }

    }

  }
}
